﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using DataEntity;
using JScripter;
using BusinessLogic.Controller;

public partial class Admin_AjaxPages_LocalityAdd : AjaxPage
{
    private Guid ID
    {
        get
        {
            if (Request.Params["lid"] != null || AjaxState.ContainsKey("lid"))
            {
                if (!AjaxState.ContainsKey("lid"))
                    AjaxState["lid"] = Request.Params["lid"];
                return new Guid(AjaxState["lid"]);
            }
            else
            {
                return Guid.Empty;
            }
        }
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (!this.IsAjaxPostBack)
        {
            new CityController().BindCity(ddCityID);
        }

        if (ID != Guid.Empty)
        {
            BindData();
        }
    }


    private void AddData()
    {
        try
        {
            Locality objLocality = new Locality();

            objLocality.LocalityID = Guid.NewGuid();

            objLocality.LocalityName = HtmlHelper.ControlValue(txtLocalityName.ClientID);

            objLocality.CityID = new Guid(HtmlHelper.ControlValue(ddCityID.ClientID));

            objLocality.ModifiedDate = DateTime.Now;

            new LocalityController().Add(objLocality);

            Response.Redirect("~/Admin/AjaxPages/LocalityList.aspx");
        }
        catch (Exception ex)
        {
            divMessage.InnerHtml = "<div class='error'>" + ex.Message + "</div>";
        }
    }

    private void EditData()
    {

        Locality objLocality = new Locality();

        objLocality.LocalityID = ID;

        objLocality.LocalityName = HtmlHelper.ControlValue(txtLocalityName.ClientID);

        objLocality.CityID = new Guid(HtmlHelper.ControlValue(ddCityID.ClientID));

        objLocality.ModifiedDate = DateTime.Now;

        new LocalityController().UpdateByLocalityID(objLocality);

        Response.Redirect("~/Admin/AjaxPages/LocalityList.aspx");
    }

    private void BindData()
    {
        var dataBunch = new LocalityController().GetbyLocalityID(ID);
        if (dataBunch.Count > 0)
        {
            var data = dataBunch[0];

        
            txtLocalityName.Text = data.LocalityName;

            new CityController().BindCity(ddCityID,data.CityID.ToString());

            

        }
    }

    protected void AddAjaxClick(object sender, AjaxControl.AjaxEventArg e)
    {
        AddData();
        
    }
    public void PreventData()
    {
        txtLocalityName.Text = HtmlHelper.ControlValue(txtLocalityName.ClientID);

        

    }

    protected void UpdateAjaxClick(object sender, AjaxControl.AjaxEventArg e)
    {
        EditData();
    }
}